package com.example.videostream.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class VideoController {

    /**
     * 适用于较小的视频文件或者需要逐块读取的大文件
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/getStream")
    public void getStream1(@RequestParam("path") String path,HttpServletResponse response) throws IOException {
        // 替换为你的视频文件路径
//        Path videoPath = Paths.get("D://google_download/航拍视频/example.mp4");
        Path videoPath = Paths.get(path);
        File videoFile = videoPath.toFile();

        response.setContentType("video/mp4");
        response.setContentLengthLong(videoFile.length());

        try (InputStream inputStream = new FileInputStream(videoFile);
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.flush();
        }
    }

    /**
     * 适用于需要设置响应头或者需要处理不同类型媒体文件的情况
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/getLongStream")
    public ResponseEntity<Resource> getLongStream(@RequestParam("path") String path) throws IOException {
        // 替换为你的视频文件路径
//        Path videoPath = Paths.get("D://google_download/航拍视频/example.mp4");
        Path videoPath = Paths.get(path);

        File videoFile = videoPath.toFile();

        Resource resource = new UrlResource(videoFile.toURI());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("video/mp4"));
        headers.setContentLength(videoFile.length());

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

}
